package com.dgut.app.service.impl;

import com.dgut.app.service.DiaryService;
import com.dgut.common.dto.DiaryDTO;
import com.dgut.common.dto.PageDTO;
import com.dgut.common.entity.Attachment;
import com.dgut.common.entity.Diary;
import com.dgut.common.entity.WxUser;
import com.dgut.common.enums.AttachTypeEnum;
import com.dgut.common.mapper.AttachmentMapper;
import com.dgut.common.mapper.DiaryMapper;
import com.dgut.common.utils.*;
import com.dgut.common.vo.DiaryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author IT00ZYQ
 * @Date 2021/4/5 13:21
 **/
@Service
public class DiaryServiceImpl implements DiaryService {

    private final DiaryMapper diaryMapper;
    private final AttachmentMapper attachmentMapper;
    public DiaryServiceImpl(DiaryMapper diaryMapper, AttachmentMapper attachmentMapper) {
        this.diaryMapper = diaryMapper;
        this.attachmentMapper = attachmentMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDiary(DiaryDTO dto, String token) {
        WxUser user = JwtUtil.getUser(token);
        Diary diary = Diary.builder()
                .content(dto.getContent())
                .title(dto.getTitle())
                .userId(user.getId())
                .build();
        diaryMapper.insert(diary);

        if (!dto.getFileIds().isEmpty()) {
            // 日记有附件，更新附件信息，将附件与日记绑定
            List<Attachment> attachments = attachmentMapper.selectBatchIds(dto.getFileIds());
            for (Attachment attachment : attachments) {
                attachment.setType(AttachTypeEnum.DIARY_ATTACHMENT.getCode());
                attachment.setDiaryId(diary.getId());
                attachmentMapper.updateById(attachment);
            }
        }
    }

    @Override
    public PageVO listDiary(String token, PageDTO dto, Date begin,Date end) {
        WxUser user = JwtUtil.getUser(token);
        return PageVO.convert(diaryMapper.listDiary(P.page(dto), user.getId(),begin,end));
    }

    @Override
    public DiaryVO detail(Integer diaryId) {
        return diaryMapper.detail(diaryId);
    }

    @Override
    public void deleteById(Integer id) {
        diaryMapper.deleteById(id);
    }

    @Override
    public void updateDiary(DiaryDTO dto) {
        if (dto.getId() == null) {
            throw new ApiException(ErrorEnum.PARAM_ERROR);
        }
        Diary diary = diaryMapper.selectById(dto.getId());
        BeanUtils.copyProperties(dto, diary);
        diaryMapper.updateById(diary);
    }
}
